package Tree._449_SerializeandDeserializeBST;

import Tree.TreeNode;

public class Codec {
    StringBuffer serialSb;
    int pos = 1;
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        this.serialSb = new StringBuffer();
        preOrder(root);
        return serialSb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("#!")) return null;
        String[] nodes = data.split("!");
        TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
        for (int i = 1; i < nodes.length; i++) {
            buildTree(root,nodes);
        }
        return root;
    }

    //serial preorder
    private void preOrder(TreeNode root) {
        if (root == null) {
            serialSb.append("#!");
        } else {
            serialSb.append(root.val + "!");
            this.preOrder(root.left);
            this.preOrder(root.right);
        }
    }

    //deserialize recursion
    private void buildTree(TreeNode root, String[] nodes) {
        if (pos > nodes.length - 1) {
            return;
        }
        if (nodes[pos].equals("#")) {
            root.left = null;
            pos++;
        } else {
            TreeNode temp = new TreeNode(Integer.parseInt(nodes[pos]));
            root.left = temp;
            pos++;
            buildTree(root.left, nodes);
        }
        if (nodes[pos].equals("#")) {
            root.right = null;
            pos++;
        } else {
            TreeNode temp = new TreeNode(Integer.parseInt(nodes[pos]));
            root.right = temp;
            pos++;
            buildTree(root.right, nodes);
        }
    }
}
